from fastapi import Query, HTTPException
from ..dependencies import me, success, router, depens
from ..models.order import Order, Refund, OrderItem, OrderAddress
from ..models.user import Address
from ..models.item import ItemComment
from ..models.base import Item, Shop
from typing import Dict, List
from pydantic import BaseModel, Field
from random import randint
from datetime import datetime
from ..services.item import checkItems
## from peewee import CSVSerializer

class OrderItemForm(BaseModel):
    item_id: int = Field(title='商品',default=0, required=True)
    number: int = Field(title='数量', default=1, ge=1, required=True)

class OrderForm(BaseModel):
    pay_type: int = Field(title='支付类型',default=0)
    address_id: int = Field(title='地址ID', default=0, ge=1, required=True)
    expr_type: int = Field(title='物流类型', default=0, required=True)
    list: List[OrderItemForm] = Field(title='商品', default=[], required=True)

### 列表
@router.get('/order', tags=["order"], dependencies=depens())
async def index(state: int = Query(embed=True, default=0), page: int = 1, size: int = 10):
    where = [Order.user_id==me('id')]
    if state > 0:
        where.append(Order.state==state)
    rows = [{**row.__data__, 'shop_name': row.shop_id.name, 'items': [item.__data__ for item in row.items]} for row in Order
            .select(Order.id, Order.state, Order.pay_state, Shop.id, Shop.name)
            .join(Shop).switch(Order).join(OrderItem).where(*where).order_by(Order.id.desc()).paginate(page, size)]
    return success({
        'list': rows,
        'total': Order.select().where(*where).count()
    })
### 读取
@router.get('/order/{id}', tags=["order"], dependencies=depens())
async def read(id: str):
    model = Order.select().join(Shop).where(Order.id==id).get()
    address = OrderAddress.get(OrderAddress.order_id==id).__data__ if model.expr_type > 0 else None
    
    return success({**model.__data__, 'shop_name': model.shop_id.name, 'address': address, 'items': [item.__data__ for item in model.items]})
### 创建
@router.post('/order', tags=["order"], dependencies=depens())
async def save(post: OrderForm):
    checkItems(post.list)
    id: str = datetime.now().strftime("%Y%m%d%H%M%S") + str(randint(1000, 9999))
    model = Order.create(id=id, user_id=me('id'), **post.__dict__)
    ids: List[int] = [row.item_id for row in post.list]
    items = Item.select(Item.id.alias('item_id'), Item.name, Item.price, Item.thumb).where(Item.id.in_(ids)).dicts()
    OrderItem.insert([{**row, 'order_id': id, 'number': 1} for row in items]).execute()
    address = Address.select(Address.consignee, Address.mobile, Address.dist_id, Address.detail).where(Address.id==post.address_id).first()
    
    OrderAddress.insert({**address.__data__, 'order_id': id}).execute()
    return success(model.__data__)

### 催发货
@router.put('/order/{id}/urg', tags=["order"], dependencies=depens())
async def update(id: int):
    model = Order.select(Order.id, Order.state).where(Order.id==id, Order.user_id==me('id')).first()
    if model.state != 2:
        raise HTTPException(403, '当前订单不是待发货状态')
    return success(model.__data__)

### 确认收货
@router.put('/order/{id}/receive', tags=["order"], dependencies=depens())
async def update(id: int):
    model = Order.select(Order.id, Order.state).where(Order.id==id, Order.user_id==me('id')).get()
    if model.state != 2 and model.state != 3:
        raise HTTPException(403, '当前订单不是待收货状态')
    model.state = 4
    model.save()
    return success(model.__data__)

### 更新
@router.put('/order/{id}', tags=["order"], dependencies=depens())
async def update(id: int, params: OrderForm):
    model = Order.update(params.__dict__).where(Order.id==id, Order.user_id==me('id')).execute()
    return success(model.__data__)

### 订单地址
@router.put('/order-address/{id}', tags=["order"], dependencies=depens())
async def update(id: int, params: OrderForm):
    order = Order.select(Order.state).where(Order.id==id, Order.user_id==me('id')).first()
    if order.state >= 2:
        raise HTTPException(403, '当前订单不支持修改地址')
    address = Address.select(Address.consignee, Address.mobile, Address.dist_id,Address.detail).where(Address.id==params.address_id).first()
    OrderAddress.update(**address.__data__).where(OrderAddress.order_id==id).execute()
    return success()

### 删除
@router.delete('/order/{id}', tags=["order"], dependencies=depens())
async def delete(id: int):
    Order.delete().where(Order.id==id, Order.user_id==me('id')).execute()
    return success()

#################
##### 订单评价 ######
#################
### 列表
@router.get('/comment', tags=["order"], dependencies=depens())
async def index(state: int = Query(embed=True, default=0), page: int = 1, size: int = 10):
    where = [Order.user_id==me('id'), Order.state>=4, OrderItem.is_evaluate==state]
    list = [row for row in OrderItem.select().join(Order, on=(Order.id==OrderItem.order_id)).where(*where).order_by(OrderItem.id.desc()).paginate(page, size).dicts()]
    return success({
        'list': list,
        'total': OrderItem.select().join(Order, on=(Order.id==OrderItem.order_id)).where(*where).count()
    })
### 提交
class CommentForm(BaseModel):
    order_item_id: int = Field(title='商品', default=0, required=True)
    content: str = Field(title='数量', default='', required=True)

@router.post('/comment', tags=["order"], dependencies=depens())
async def save(post: CommentForm):
    orderItem = OrderItem.select().join(Order).where(OrderItem.id==post.order_item_id, Order.state>=4, OrderItem.is_evaluate==0, Order.user_id==me('id')).get()
    ItemComment.create(item_id=orderItem.item_id, user_id=me('id'), **post.__dict__)
    OrderItem.update({'is_evaluate': 1}).where(OrderItem.id==post.order_item_id).execute()
    return success()

#################
##### 退款 ######
#################
class RefundForm(BaseModel):
    id: str = Field(description="收货人", default='', max_length=20)
    number: str = Field(description="手机号", default='', max_length=11)

### 列表
@router.get("/refund", tags=["order"], dependencies=depens())
async def index(page: int = 1, size: int = 10):
    list = [row for row in Refund.select().join(OrderItem).where(Refund.user_id==me('id')).order_by(Refund.order_item_id.desc()).paginate(page, size).dicts()]
    return success({
        'list': list,
        'total': Refund.select().where(Refund.user_id==me('id')).count()
    })
### 读取
@router.get('/refund/{id}', tags=["order"], dependencies=depens())
async def read(id: int):
    model = Refund.get(Refund.id == id)
    return success(model.__data__)
### 添加
@router.get('/refund/{id}/add', tags=["order"], dependencies=depens())
async def read(id: int):
    model = Order.select().join(Shop).where(Order.id==id, Order.user_id==me('id')).get()
    items = OrderItem.select().where(OrderItem.order_id==id).dicts()
    return success({**model.__data__, 'shop_name': model.shop_id.name, 'items': [row for row in items]})
### 创建
@router.post('/refund', tags=["order"], dependencies=depens())
async def save(post: RefundForm):
    ## item = OrderItem.select(OrderItem.id, OrderItem.name, OrderItem.thumb, OrderItem.price).where(OrderItem.id==post.id).get()
    model = Refund.create(id=datetime.now().strftime("%Y%m%d%H%M%S") + str(randint(1000, 9999)), user_id=me('id'))
    return success(model.__data__)
### 更新
@router.put('/refund/{id}', tags=["order"], dependencies=depens())
async def update(id: int, model: RefundForm):
    Refund.update(model.__dict__).where(Refund.id==id, Refund.user_id==me('id')).execute()
    return success()
### 删除
@router.delete('/refund/{id}', tags=["order"], dependencies=depens())
async def delete(id: int):
    Refund.delete().where(Refund.id==id, Refund.user_id==me('id')).execute()
    return success()


#################
##### 订单物流 ######
#################
### 列表
@router.get('/deivery', tags=["order"], dependencies=depens())
async def index(state: int = Query(embed=True, default=0), page: int = 1, size: int = 10):
    where = [Order.user_id==me('id')]
    if state > 0:
        where.append(Order.state==state)
    list = [row for row in OrderItem.select().join(Order, on=(Order.id==OrderItem.order_id)).where(*where).order_by(OrderItem.id.desc()).paginate(page, size).dicts()]
    return success({
        'list': list,
        'total': OrderItem.select().join(Order, on=(Order.id==OrderItem.order_id)).where(*where).count()
    })
### 提交
@router.post('/deivery', tags=["order"], dependencies=depens())
async def update(id: int, params: Dict = {}):
    model = OrderItem.update(params).where(OrderItem.id==id).execute()
    return success(model.__data__)
